﻿
@{
    ViewBag.Title = "Chat";
}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<link href="../../Content/css/indexstyle.css" rel="stylesheet" />
<body>
    <div class="header">

    </div>
    <div class="center">
        <div class="left">
            <div class="listheader">
                <ul>
                    <li>
                        <div class="btn_historylist  active" onclick="listHeaderClick('history')">会话</div>
                    </li>
                    <li>
                        <div class="btn_userlist" onclick="listHeaderClick('user')">列表</div>
                    </li>
                    <li>
                        <div class="btn_grouplist" onclick="listHeaderClick('group')">群组</div>
                    </li>
                </ul>
            </div>
            <div class="listcontent">
                <div class="list listhistory  active">

                </div>
                <div class="list listuser">
                    
                </div>
                <div class="list listgroup">

                </div>
            </div>
        </div>
        <div class="right">
            <div class="conversationbody">
                <div class="conversationtop">
                    <span class="textname"></span>
                </div>
                <div class="conversationcenter">
                    <div class="converleft">
                        <div class="convercontent">

                        </div>
                        <div class="convermessage">
                            <textarea name="message" id="message"></textarea>
                            <div class="btnsend" onclick="btnSendClick()">发送</div>
                        </div>
                    </div>
                    <div class="converright">
                        <h5>成员</h5>
                        <div class="memberlist">
                            
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div>
        <input type="hidden" id="touin" value="0" />
        <input type="hidden" id="uintype" />
    </div>
    <div class="historymsg" style="visibility:hidden">

    </div>
</body>


<script src="../../Content/js/jquery-2.2.3.min.js"></script>
<script src="../../Content/js/listmanager.js"></script>
<script src="../../Content/js/template.js"></script>
<script>

    var socket;
    var socketUrl = "ws://localhost:58785/WebChat/ChatSocket?uinid=@ViewBag.UinId";



function WebChatConnect(url) {
    socket = new WebSocket(url);

    socket.onclose = (event) => {
        //alert("掉线 close");
        WebChatConnect(url);
    };
    socket.onerror = (event) => {
        //alert("掉线 error");
        WebChatConnect(url);
    };
    socket.onmessage = (event) => {

        try {
            var data = JSON.parse(event.data);
            //接收消息
            if (data.Action == "msg") {
                //如果当前对话框和收到的消息来源一致，则显示，否则只提示新消息
                if ($("#touin").val() == data.Content.From_uin) {
                    $(".listcontent .listitem").each((index, value) => {
                        if ($(".uinid", value).text() == data.Content.Send_uin) {
                            LoadOtherMessage($(".uinname", value).text(), data.Content.Content);
                            socket.send(JSON.stringify({ Action: "readed", Content: data.Content.Id }))
                            return false;
                        }
                    });
                }
                else {
                    //TODO 如果消息跟当前对话框不一致，则提示未读消息
                }
            }
            else if (data.Action == "updatelist") {
                LoadUsers();
                LoadGroup();
                LoadMambers($("#touin").val());
            }
        } catch (e) {
            console.log(e);
        }
    };
    socket.onopen = (event) => {
        //alert("连线");
    };
}

//加载用户信息
function LoadUsers() {
    $.post("@Url.Action("GetAllUser", "WebChat")", {}, function (result) {
        var html = template("uinlisttemplate", result);
        $(".listcontent .listuser").html(html);
    });
}
//分组信息
function LoadGroup() {
    $.post("@Url.Action("GetAllGroup", "WebChat")", {}, function (result) {
        var html = template("uinlisttemplate", result);
        $(".listcontent .listgroup").html(html);
    });
}
function LoadMambers(uinid) {
    $.post("@Url.Action("GetMembers", "WebChat")", { uinid: uinid }, function (result) {
        var html = template("membertamplate", result);
        $(".memberlist").html(html);
    });
}
//载入未读消息
function LoadUnReadMessages(fromUinId) {
    socket.send(JSON.stringify({ Action: "unread", Content: fromUinId }));
}
//载入个人消息
function LoadMyMessage(content) {
    var data = { Content: content };
    var html = template("mymessagetemplate", data);
    $(".convercontent").append(html);
    $(".convercontent").scrollTop($(".convercontent")[0].scrollHeight);

}
//载入他人消息
function LoadOtherMessage(username, content) {
    var data = { Uinname: username, Content: content };
    var html = template("othermessagetemplate", data);
    $(".convercontent").append(html);
    $(".convercontent").scrollTop($(".convercontent")[0].scrollHeight);
}
//发送
function btnSendClick() {
    if ($("#touin").val() == "0") {
        alert("请选择发送对象");
        return;
    }
    var content = $("#message").val();
    if (content.trim().length == 0) alert("不允许发空消息");
    LoadMyMessage(content);
    //发送
    data = { Action: "msg", Content: { To_uin: $("#touin").val(), Content: content } };
    if (socket.readyState == WebSocket.OPEN) {
        socket.send(JSON.stringify(data));
    }
    else {
        WebChatConnect(socketUrl);
        socket.send(JSON.stringify(data));
    }
    $("#message").val("");
}
//发送快捷键监听
function sendListener() {
    $("#message").keyup(event => {
        if (event.ctrlKey && event.keyCode == 13)//CTRL+回车
            btnSendClick();
    });
}


function checkAndSaveHistorymsg(fromuinid) {
    //保存当前记录
    if ($("#touin").val() != "0") {
        var currentHistoryMsg = $(".historymsg .historymsg_" + $("#touin").val());
        if (currentHistoryMsg.length == 0)//没有记录
        {
            $("<div></div>").attr("class", "historymsg_" + $("#touin").val()).html($(".convercontent").html()).appendTo($(".historymsg"));
        }
        else {
            currentHistoryMsg.html($(".convercontent").html());
        }
    }

    //显示历史纪录
    var oldHistoryMsg = $(".historymsg .historymsg_" + fromuinid);
    if (oldHistoryMsg.length == 0)//没有记录
    {
        $(".convercontent").html("");
    }
    else {
        $(".convercontent").html(oldHistoryMsg.html());
    }
}


function listItemClick(obj) {
    var uinid = $(".uinid", obj).text();
    var listhistory = $(".listhistory");
    var listitems = $(".listitem", listhistory);
    var uin = null;
    //查看列表是否已经存在对话记录

    listitems.each(function (i, v) {
        $(v).removeClass("active");
        var tempuinid = $(".uinid", v).text();
        if (tempuinid == uinid) {
            uin = v;
        }
    });

    if (!uin) {
        uin = $(obj).clone();
        listhistory.append(uin);
    }
    $(uin).addClass("active");
    $(".listcontent .list").hide();
    $(".listcontent .listhistory").show();
    $(".listheader div").removeClass("active");
    $(".listheader .btn_historylist").addClass("active");
    //载入页面历史记录
    checkAndSaveHistorymsg(uinid);
    //设置值
    $(".conversationtop .textname").text($(".uinname", uin).text());
    $("#touin").val($(".uinid", uin).text());
    $("#uintype").val($(".uintype", uin).val());

    //载入右侧边成员信息
    LoadMambers(uinid);
    //载入未读消息
    LoadUnReadMessages(uinid);
}

function listHeaderClick(listclass) {
    $(".listcontent .list").hide();
    $(".listheader div").removeClass("active");
    switch (listclass) {
        case "history":
            $(".listheader .btn_historylist").addClass("active");
            $(".listcontent .listhistory").show();
            break;
        case "user":
            $(".listheader .btn_userlist").addClass("active");
            $(".listcontent .listuser").show();
            break;
        case "group":
            $(".listheader .btn_grouplist").addClass("active");
            $(".listcontent .listgroup").show();
            break;
    }
    }

    $(document).ready(function () {
        //LoadUsers();
        //LoadGroup();
        WebChatConnect(socketUrl);
        sendListener();
    });

</script>
<!-- 模板 -->
<script id="uinlisttemplate">
    {{each data}} <div class="listitem" onclick="listItemClick(this)" > <img src="../../Content/content/loginheader.jpg" height="40" width="40" alt="" > <div class="uininfo" > <div class="uinname" >{{ $value.Uin_name}}</div> <div class="uinid" >{{ $value.Id}}</div> <input type="hidden" class="uintype" value="{{$value.Uin_type}}" /> </div> </div > {{/each}}
</script>
<script id="membertamplate">
    {{ each data}} <div class="listitem" > <img src="../../Content/content/loginheader.jpg" height="22" width="22" alt="" > <div class="uininfo" > <div class="uinname" >{{ $value.Uin_name }}<input type="hidden" class="uinid" value="{{ $value.Id}}" /></div> </div > </div> {{/each}}
</script>
<script id="othermessagetemplate">
    <div class="othermessage" > <div class="listitem" > <img src="../../Content/content/loginheader.jpg" height="26" width="26" alt="" > <div class="uininfo" > <div class="uinname" >{{ Uinname}}</div> <div class="content" >{{Content }}</div> </div > </div> </div ><br /><br />
</script>
<script id="mymessagetemplate">
    <div class="mymessage" > <div class="listitem" > <img src="../../Content/content/loginheader.jpg" height="26" width="26" alt="" > <div class="uininfo" >  <div class="uinname" > </div> <div class="content" >{{#Content }}</div> </ div > </div> </ div ><br /><br />
</script>
<!-- 模板 end-->
</html>

